<template>
  <div class="app-container project-create-edit-bom">


    <el-card>
      <div slot="header" class="clearfix ">
        <el-row>
          <el-col :span="1">
            <el-link icon="el-icon-arrow-left" @click="$tab.closePage(view).then(({ visitedViews }) => {
                if (this.isActive(view)) {
                  this.toLastView(visitedViews, view)
                }
              });$router.go(-1)">返回
            </el-link>
          </el-col>
          <el-col :span="22">
            <div class="flex1 flex-row align-center justify-center"> 项目信息</div>
          </el-col>
          <el-col :span="1">
            <el-link></el-link>
          </el-col>
        </el-row>
      </div>
      <el-form v-show="showSearch" ref="projectForm" :inline="true" :model="projectForm" label-width="100px">
        <el-form-item label="项目名" prop="projectName">
          <el-input v-model="projectForm.projectName" placeholder="请输入项目名"/>
        </el-form-item>
        <el-form-item label="项目编码" prop="projectCode">
          <el-input v-model="projectForm.projectCode" placeholder="请输入项目编码"/>
        </el-form-item>
        <el-form-item label="客户名称" prop="customerId">
          <el-input v-model="projectForm.customerId" placeholder="请输入客户名称"/>
        </el-form-item>
        <el-form-item label="销售订单编号" prop="salesOrderId">
          <el-input v-model="projectForm.salesOrderId" placeholder="请输入销售订单编号"/>
        </el-form-item>
        <el-form-item label="BOM成本" prop="costAmount">
          <el-input v-model="projectForm.costAmount" placeholder="请输入BOM成本"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="projectForm.remark" placeholder="请输入备注"/>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="projectForm.startTime"
                          clearable
                          placeholder="请选择开始时间"
                          style="width:200px;"
                          type="date"
                          value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="projectForm.endTime"
                          clearable
                          placeholder="请选择结束时间"
                          style="width:200px;"
                          type="date"
                          value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <el-row justify="end" type="flex">
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-row>

      <el-divider></el-divider>

      <el-row>
        <el-col :span="24" class="flex-row align-center justify-center">
          项目BOM信息
        </el-col>
      </el-row>
      <el-container>
        <el-main v-if="!data.length">
          <el-empty :image-size="200"></el-empty>
        </el-main>
        <el-container v-else>
          <el-aside width="auto!important">
            <el-tree
              ref="elTree"
              :data="data"
              :expand-on-click-node="false"
              default-expand-all
              node-key="id"
              @node-click="nodeClick">
              <div slot-scope="{ node, data }" class="flex1 flex-row">
                <div class="flex1">{{ data.goodsName }}</div>
                <div style="width: 20px"></div>
                <div>
                  <el-tag v-if="data.id" size="mini">
                    数量：{{ data.bomQty }}
                  </el-tag>
                </div>
                <div style="width: 20px"></div>
                <el-button
                  icon="el-icon-plus"
                  size="mini"
                  type="text"
                  @click.stop="append(data)">
                  添加
                </el-button>
                <div style="width: 20px"></div>
                <el-button
                  class=""
                  icon="el-icon-delete"
                  size="mini"
                  type="text"
                  @click.stop="remove(node, data)">
                  删除
                </el-button>
              </div>
            </el-tree>
          </el-aside>
          <el-main>
            <Form ref="Form" :oldFormData="oldFormData" :formData="form" :is-from-project="true" :show-obj="showObj" @formChange="formChange"
                  @onSubmit="onSubmit"></Form>
          </el-main>
        </el-container>
      </el-container>
    </el-card>

  </div>
</template>

<script>
import {delProjectBom, getNoPageList} from "@/api/prdmgt/projectBom";
import {addProject, delProject, getProject, updateProject} from "@/api/prdmgt/project";
import {handleTree} from "@/utils/ruoyi";
import Form from "@/views/basic/bom/components/Form";

const showOrHide = (data) => {
  return {
    goodsId: true,
    goodsName: true,
    goodsCode: true,
    goodsBatch: true,
    goodsCategory: true,
    spec: true,
    barcode: true,
    prePurchasePrice: true,
    unit: true,
    bomQty: true,
    submit: true,
    cancel: true,
    bom_qty: true,
    total_cost: true,
    req_time: true,
    is_picked: true,
    start_time: true,
    end_time: true,
  }
}

export default {
  name: "ProjectBom",
  components: {
    Form
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目BOM表格数据
      bomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      projectForm: {
        projectId: null,
        parentId: null,
        goodsId: null,
        goodsName: null,
        goodsCode: null,
        goodsBatch: null,
        goodsCategory: null,
        spec: null,
        barcode: null,
        prePurchasePrice: null,
        unit: null,
        unitRatedCost: null,
        bomQty: null,
        totalCost: null,
        reqTime: null,
        isPicked: null,
        startTime: null,
        endTime: null,
        createId: null,
        updateId: null,
      },
      // 表单校验
      rules: {},
      data: [],
      id: '',
      form: {
        id: null,
        name: null,
        code: null,
        parentId: null,
        goodsId: null,
        goodsName: null,
        goodsCode: null,
        goodsBatch: null,
        goodsCategory: null,
        spec: null,
        barcode: null,
        prePurchasePrice: null,
        unit: null,
        bomQty: null,
        totalCost: null,
        reqTime: null,
        isPicked: null,
        startTime: null,
        endTime: null,
      },
      oldFormData:{},
      showObj: showOrHide(),
      tableData: [],
      isFormChange: false
    };
  },
  created() {
    if (this.$route.params.id) {
      this.id = this.$route.params.id
      this.initData()
      this.getNoPageListFn()
    }
  },
  mounted() {
    this.$nextTick(() => {
      document.querySelector('.el-container').style.height = `calc( 100vh - ${document.querySelector('.el-container').offsetTop}px - 140px)`
    })
  },
  methods: {
    async canHandleEvent() {
      return await new Promise(async (resolve, reject) => {
        if (this.isFormChange) {
        await  this.$modal.confirm('当前有数据未保存,是否保存',{confirmButtonText:'保存'}).then(() => {
              this.$refs.Form.submit(()=>{
                debugger
                resolve()
              })
          }).catch(() => {
              resolve()
          });
        } else {
          await  resolve()
        }
      })
    },
    formChange(status) {
      this.isFormChange = status
    },
    async initData() {
      await getProject(this.id).then(response => {
        this.projectForm = response.data;
      });
    },
    async getNoPageListFn() {
      await getNoPageList(this.id).then(res => {
        this.data = handleTree(res.data)
        if (!this.data.length) {
          this.data.push({
            label: "",
            parentId: 0
          })
          this.form.projectId = this.projectForm.id
          this.form.status = 'add'
        } else {
          if(this.form.status != 'add'  ){
            this.form = {
              ...(  res.data.find(d=>d.id === this.form.id) || res.data[0]   )
            }
            this.oldFormData = JSON.parse(JSON.stringify(this.form))
          }else {
            this.form = {
              status :'view',
              ...res.data[res.data.length-1]
            }
            this.oldFormData = JSON.parse(JSON.stringify(this.form))
          }
        }

      })
    },
    onSubmit() {
      this.getNoPageListFn()
    },
    nodeClick(data, Node) {
      this.canHandleEvent().then(res => {
        this.contentFormData('view', data, Node)
      })
    },
    contentFormData(status, data, Node) {
      if (status === 'add') {
        this.form = {
          status,
          projectId: this.projectForm.id,
          id: null,
          parentId: data.id || 0,
          name: data.name,
          code: data.code
        }
      } else if (status === 'view') {
        this.form = {
          status,
          ...data,
        }
      }
      this.oldFormData = JSON.parse(JSON.stringify(this.form))
      this.isFormChange = false
    },
    /** 删除按钮操作 */
    remove(node, row) {
      if (!row.id) return
      const ids = [row.id];
      this.canHandleEvent().then(res => {
        this.$modal.confirm('是否确认删除' + (row.name || row.goodsName) + '数据项？').then(function () {
          return delProjectBom(ids);
        }).then(() => {
          this.initData()
          this.getNoPageListFn()
          this.reset();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      })

    },
    append(data, Node) {
      this.canHandleEvent().then(res => {
        this.contentFormData('add', data, Node)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        parentId: null,
        goodsId: null,
        goodsName: null,
        goodsCode: null,
        goodsBatch: null,
        goodsCategory: null,
        spec: null,
        barcode: null,
        prePurchasePrice: null,
        unit: null,
        unitRatedCost: null,
        bomQty: null,
        totalCost: null,
        reqTime: null,
        isPicked: null,
        startTime: null,
        endTime: null,
        remark: null,
        delFlag: null,
        createId: null,
        createBy: null,
        createTime: null,
        updateId: null,
        updateBy: null,
        updateTime: null
      };
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["projectForm"].validate(valid => {
        if (valid) {
          if (this.projectForm.id != null) {
            updateProject(this.projectForm).then(response => {
              this.initData()
              this.getNoPageListFn()
              this.$modal.msgSuccess("修改成功");
            });
          } else {
            addProject(this.projectForm).then(response => {
              this.id = response.data.id
              this.initData()
              this.getNoPageListFn()
              this.$modal.msgSuccess("新增成功");
            });
          }
        }
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("projectForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除项目BOM编号为"' + ids + '"的数据项？').then(function () {
        return delProjectBom(ids);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('prdmgt/bom/export', {
        ...this.projectForm
      }, `bom_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss">
.project-create-edit-bom {

  aside {
    background: #fff;
    border-right: 3px solid #eef1f6;
  }

  el-main
  .custom-tree-node {
    .el-button [class*=el-icon-] + span {
      margin-left: 0;
    }
  }

}
</style>
